package com.wtp.wallpaper.controller.user;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wtp.wallpaper.annotation.ReplaceURL;
import com.wtp.wallpaper.common.constant.PictureOssPathConstant;
import com.wtp.wallpaper.common.constant.UserUploadConstant;
import com.wtp.wallpaper.common.context.BaseContext;
import com.wtp.wallpaper.pojo.dto.UserDTO;
import com.wtp.wallpaper.pojo.dto.ValidateDTO;
import com.wtp.wallpaper.pojo.entity.User;
import com.wtp.wallpaper.pojo.entity.UserUpload;
import com.wtp.wallpaper.pojo.query.PageQuery;
import com.wtp.wallpaper.pojo.vo.PictureVO;
import com.wtp.wallpaper.pojo.result.Result;
import com.wtp.wallpaper.service.PictureService;
import com.wtp.wallpaper.service.UserService;
import com.wtp.wallpaper.service.UserUploadService;
import com.wtp.wallpaper.utils.AliOssUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserUploadService userUploadService;

    @Autowired
    private PictureService pictureService;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/validate")
    public Result getValidateCode(@RequestBody ValidateDTO validateDTO){
        log.info("当前手机号:{}",validateDTO);
        //String res = aliyunSmsUtil.sendRegister(validateDTO.getPhone());
        String res = "1111";
        log.info("生成验证码:{}",res);

        String uuid = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(uuid,res,5, TimeUnit.MINUTES);
        return Result.success(ValidateDTO.builder()
                .validateId(uuid)
                .phone(validateDTO.getPhone())
                .build());
    }

    @PostMapping("/login")
    public Result validate(@RequestBody UserDTO userDTO){
        //System.out.println("66666666666666");
        log.info("用户{}登录",userDTO);
        Object o = redisTemplate.opsForValue().get(userDTO.getValidateId());
        if (o == null || !o.equals(userDTO.getValidateCode())){
            return Result.error("验证码错误!");
        }

        User user = BeanUtil.copyProperties(userDTO, User.class);
        return Result.success(userService.login(user));
    }
    @GetMapping("/userinfo")
    public Result getUserInfo(){
        return Result.success(userService.getUserInfo(BaseContext.getCurrentId()));
    }

    @GetMapping("/userWallList")
    @ReplaceURL
    public Result getUserWall(@RequestParam(defaultValue = "1") int pageNum,
                              @RequestParam(defaultValue = "5") int pageSize,
                              @RequestParam("type") String type){

        List<PictureVO> list = userService.getUserWallByType(new PageQuery(pageNum,pageSize),type);
        return Result.success(list);
    }


    @PostMapping("/user/uploadBatch")
    public Result uploadBatch(MultipartFile file, HttpServletRequest request) throws IOException {

        String filename = null;
        String fileMd5 = null;
        try {
            //判断图片是否重复

            Object[] repeat = pictureService.isRepeat(file.getInputStream());
            fileMd5 = (String) repeat[0];
            boolean exists = userUploadService.exists(new QueryWrapper<UserUpload>().eq("file_md5", fileMd5));
            if(repeat[1].equals(true) || exists){
                return Result.error("图片已存在!");
            }

            filename = file.getOriginalFilename();
            assert filename != null;
            filename = UUID.randomUUID() + filename.substring(filename.lastIndexOf('.'));

            filename = PictureOssPathConstant.PIC_UPLOAD_URL + "/" + filename;
            aliOssUtil.upload(file.getBytes(),filename);

            String classifyId = request.getHeader("classify_id");
            String description = request.getHeader("description");
            description = URLDecoder.decode(description, StandardCharsets.UTF_8);
            UserUpload userUpload = UserUpload.builder()
                    .userId(Long.valueOf(BaseContext.getCurrentId()))
                    .picurl(filename)
                    .classId(Long.valueOf(classifyId))
                    .description(description)
                    .state(UserUploadConstant.UNAUDITED)
                    .fileMd5(fileMd5)
                    .build();

            userUploadService.save(userUpload);

            return Result.success("上传成功");
        } catch (Exception e) {
            return Result.error("上传失败");
        }
    }
}
